var dataService = require('../../service/dataService');
var fs = require('fs');

module.exports = {
    exec: function (mapper, method, args, callback) {
        if (typeof args == 'function') {
            callback = args;
            args = {};
        }
        this.get(mapper, method, args, function (msg) {
            if (msg.result == 'fail') {
                callback(new Error(msg.result));
            } else {
                dataService.fetchData(msg.sql, args, function (err, data) {
                    callback(err, data);
                });
            }
        });
    },

    get: function (mapper, method, args, callback) {
        if (typeof args == 'function') {
            callback = args;
            args = {};
        }
        fs.exists('./mapper/' + mapper + 'Mapper.js', function (exists) {
            if (!exists) {
                callback({
                    result: 'fail'
                });
                return;
            }

            var m = require('../../mapper/' + mapper + 'Mapper');
            if (!m[method]) {
                callback({
                    result: 'fail'
                });
                return;
            }

            callback({
                result: 'ok',
                sql: m[method](args)
            });
        });
    }
};